package cn.tedu.icop.order.mqtt;

import cn.tedu.icop.order.constant.Constants;
import cn.tedu.icop.order.constant.MqttConstant;
import cn.tedu.icop.order.constant.OrderStatusConstant;
import cn.tedu.icop.order.context.OrderContext;
import cn.tedu.icop.order.dao.mapper.OrderSuccessMapper;
import cn.tedu.icop.order.pojo.dto.ChargingResultDto;
import cn.tedu.icop.order.pojo.po.ChargingBillFailPO;
import cn.tedu.icop.order.pojo.po.ChargingBillSuccessPO;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
public class MqttConsumer implements MqttCallbackExtended {

    private MqttClient mqttClient;
    private OrderContext orderContext;
    public MqttConsumer(MqttClient mqttClient, OrderContext orderContext){
        this.mqttClient=mqttClient;
        this.orderContext=orderContext;
    }

    @Override
    public void connectComplete(boolean reconnect, String serverURI) {
        log.debug("MqttConsumer#connectComplete方法被调用了,表示连接成功," +
                "reconnect:{},serverURI:{}",reconnect,serverURI);
        try {
            log.debug("连接成功,订阅开始充电指令的响应topic:{}","/topic/start/charging/result");
            mqttClient.subscribe(MqttConstant.TOPIC_START_CHARGING_RESULT);
            log.debug("连接成功,订阅开始充电指令的响应topic:{},成功.","/topic/start/charging/result");
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public void connectionLost(Throwable cause) {
        log.debug("MqttConsumer#connectionLost方法被调用了,表示连接丢失",cause);
    }
    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
           log.debug("MqttConsumer topic:{},message:{}",topic,message);
           if(topic.equals(MqttConstant.TOPIC_START_CHARGING_RESULT)){
               handleStartChargingResult(message);
           }
    }

    /**处理开始充电的结果*/
    private void handleStartChargingResult(MqttMessage message) {
        ChargingResultDto chargingResultDto =
                JSON.parseObject(message.toString(), ChargingResultDto.class);
        if(chargingResultDto!=null){
            String result = chargingResultDto.getResult();
            if(result.equals(Constants.RESULT_START_CHARGING_SUCCESS)){
                log.debug("开始充电指令执行成功,订单号:{}",chargingResultDto.getOrderNo());
                saveSuccessOrder(chargingResultDto);
            }else{
                log.debug("开始充电指令执行失败,订单号:{}",chargingResultDto.getOrderNo());
                saveFailOrder(chargingResultDto);
            }
        }
    }
    /**保存失败订单*/
    private void saveFailOrder(ChargingResultDto chargingResultDto) {
        log.debug("向失败订单表写数据,订单号:{}",chargingResultDto.getOrderNo());
        ChargingBillFailPO chargingBillFailPO=new ChargingBillFailPO();
        chargingBillFailPO.setBillId(chargingResultDto.getOrderNo());
        chargingBillFailPO.setFailDesc("设备故障无法正常充电");
        orderContext.getOrderRepository().saveFailOrder(chargingBillFailPO);
        log.debug("向失败订单表写数据,订单号:{}",chargingResultDto.getOrderNo());

    }
    /**保存成功订单*/
    private void saveSuccessOrder(ChargingResultDto chargingResultDto) {
        log.debug("向成功订单表写数据,订单号:{}",chargingResultDto.getOrderNo());
        ChargingBillSuccessPO chargingBillSuccessPO=new ChargingBillSuccessPO();
        chargingBillSuccessPO.setBillId(chargingResultDto.getOrderNo());
        chargingBillSuccessPO.setBillStatus(OrderStatusConstant.ORDER_STATUS_PROGRESS);
        orderContext.getOrderRepository().saveSuccessOrder(chargingBillSuccessPO);
        log.debug("向成功订单表写数据,订单号:{},成功",chargingResultDto.getOrderNo());
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        log.debug("MqttConsumer#deliveryComplete方法被调用了,表示消息分发完成" +
                "token:{}",token);
    }
}
